const md5 = require("md5");
const dayjs = require("dayjs");
const { Send } = require("../utils/response");
const User = require("../models/user");

class UserController {
    static async add(req, res, next) {
        try {
            const { username, password, avatar } = req.body;
            const isExist = await User.findOne({ username });
            if (isExist) {
                return Send(res, {
                    code: -1,
                    message: "该用户名已存在"
                });
            }
            const user = await User.create({
                username,
                password,
                avatar,
                regLocation: {
                    ip: req.location.ip || "",
                    country: req.location.country || "",
                    region: req.location.region || "",
                    city: req.location.city || ""
                }
            });
            return Send(res, {
                message: "创建成功",
                data: {
                    _id: user._id,
                    username: user.username,
                    avatar: user.avatar,
                    regLocation: user.regLocation,
                    lastLogin: user.lastLogin,
                    regDate: user.regDate,
                    isActive: user.isActive
                }
            });
        } catch (error) {
            next(error);
        }
    }
    static async login(req, res, next) {
        try {
            if (req.session.user) {
                return Send(res, { code: -1, message: "你已登录" });
            }
            const user = await User.findOne({
                username: req.body.username,
                password: md5(req.body.password)
            }).select("+role");
            if (!user) {
                return Send(res, {
                    code: -1,
                    message: "用户名或密码错误"
                });
            }
            if (user.role == "user") {
                return Send(res, {
                    code: -1,
                    message: "您没有权限登录管理后台"
                });
            }
            req.session.user = {
                id: user._id
            };
            user.lastLogin = dayjs().format("YYYY/MM/DD HH:mm:ss");
            await user.save();
            return Send(res, {
                message: "登录成功",
                data: {
                    id: user._id,
                    username: user.username,
                    avatar: user.avatar
                }
            });
        } catch (error) {
            next(error);
        }
    }
    static async logout(req, res, next) {
        try {
            const id = req.session.user.id;
            req.session.destroy();
            return Send(res, {
                code: 1,
                data: id,
                message: "退出登录成功"
            });
        } catch (error) {
            next(error);
        }
    }
    static async list(req, res, next) {
        try {
            const { pageno = 1, pagesize = 1000, keywords } = req.query;
            const regex = new RegExp(keywords, "i");
            const counts = await User.countDocuments({
                role: "user",
                username: { $regex: regex }
            });
            const users = await User.find({
                role: "user",
                username: { $regex: regex }
            })
                .select("+upassword")
                .sort({
                    regDate: -1,
                    isActive: 1
                })
                .skip((pageno - 1) * pagesize)
                .limit(pagesize);
            return Send(res, {
                data: {
                    pageno: parseInt(pageno),
                    pagesize: parseInt(pagesize),
                    total: counts,
                    list: users
                }
            });
        } catch (error) {
            next(error);
        }
    }
    static async info(req, res, next) {
        try {
            if (!req.session.user) {
                return Send(res, { code: 0, message: "请先登录" });
            }
            const user = await User.findOne({
                _id: req.session.user.id,
                role: "admin"
            });
            return Send(res, {
                data: {
                    _id: user._id,
                    username: user.username,
                    avatar: user.avatar,
                    lastLogin: user.lastLogin
                }
            });
        } catch (error) {
            next(error);
        }
    }
    static async delete(req, res, next) {
        try {
            const { deletedCount } = await User.deleteOne({
                _id: req.params.id,
                role: "user"
            });
            if (deletedCount === 0) {
                return Send(res, {
                    code: -1,
                    message: "该用户不存在"
                });
            }
            return Send(res, {
                message: "删除成功",
                data: req.params.id
            });
        } catch (error) {
            next(error);
        }
    }
    static async update(req, res, next) {
        try {
            if (!req.body) {
                return Send(res, {
                    code: -1,
                    message: "请填写要修改的参数"
                });
            }
            const user = await User.findByIdAndUpdate(req.params.id, req.body);
            if (!user) {
                return Send(res, {
                    code: -1,
                    message: "该用户不存在"
                });
            }
            Send(res, {
                message: "更新成功",
                data: user._id
            });
        } catch (error) {
            next(error);
        }
    }
    static async downloads(req, res, next) {
        try {
            res.send("用户的下载列表");
        } catch (error) {
            next(error);
        }
    }
    static async ratings(req, res, next) {
        try {
            res.send("用户的评分列表");
        } catch (error) {
            next(error);
        }
    }
}

module.exports = UserController;
